package com.aidong.web.inteceptor;

/**
 * Created by john on 16-11-2.
 */
import com.aidong.model.LoginUser;
import com.aidong.model.MenuAuthority;
import com.aidong.service.SysUserSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class AuthorityInteceptor implements HandlerInterceptor {
    protected Logger log = Logger.getLogger(this.getClass());
    @Resource
    private SysUserSession userSession;

    public AuthorityInteceptor() {
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
        HandlerMethod method = (HandlerMethod)obj;
        this.userSession.setLoginInfo(request);
        LoginUser aduser = this.userSession.getLoginUser();
        String modCode = method.getBeanType().getName().toLowerCase().replace("com.aidong.web.controller.", "");
        if(modCode.endsWith("controller")) {
            modCode = modCode.substring(0, modCode.length() - 10);
        }

        if(!modCode.startsWith("svc.") && !"login".equals(modCode)) {
            if(aduser == null) {
                if("XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))) {
                    response.setStatus(401);
                    this.outputResponse(response, "{ret:false, code:-1, msg:\"您还没有登录或已经超时!\"}");
                } else {
                    request.setAttribute("backUrl", request.getRequestURI());
                    request.getRequestDispatcher("/login").forward(request, response);
                }

                this.userSession.remove();
                return false;
            }

            if(aduser.getLoginStatus() != 1) {
                String authority1 = aduser.getLoginStatus() == 3?"您已在其他地方登录!":"您已经退出!";
                if("XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))) {
                    this.outputResponse(response, "{ret:false, code:-1, msg:\"" + authority1 + "\"}");
                } else {
                    request.setAttribute("msg", authority1);
                    request.setAttribute("backUrl", request.getRequestURI());
                    request.getRequestDispatcher("/login").forward(request, response);
                }

                this.userSession.addLogoutLog(aduser);
                this.userSession.removeLoginUser(request);
                this.userSession.remove();
                return false;
            }

            if(!"index".equals(modCode) && !"sys.sysmessageread".equals(modCode)) {
                MenuAuthority authority = null;
                Map authMap = (Map)request.getSession().getAttribute("menuAuth");
                if(authMap != null) {
                    authority = (MenuAuthority)authMap.get(modCode);
                }

                if(authority == null || !authority.chkAuth(method.getMethod().getName())) {
                    if("XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))) {
                        response.setStatus(403);
                        this.outputResponse(response, "{ret:false, code:-2, msg:\"您没有权限进行该操作!\"}");
                    } else {
                        request.setAttribute("backUrl", request.getRequestURI());
                        request.getRequestDispatcher("/restrict").forward(request, response);
                    }

                    this.userSession.remove();
                    return false;
                }

                this.userSession.setAuthority(authority);
            }
        }

        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView modelAndView) throws Exception {
        if(modelAndView != null && (modelAndView.getViewName() == null || !modelAndView.getViewName().startsWith("redirect:"))) {
            modelAndView.addObject("_appPath", request.getContextPath());
            LoginUser aduser = this.userSession.getLoginUser();
            if(aduser != null) {
                modelAndView.addObject("sysUser", aduser);
            }

            MenuAuthority authority = this.userSession.getAuthority();
            if(authority != null) {
                List opl = authority.getOperList();
                Iterator i$ = opl.iterator();

                while(i$.hasNext()) {
                    String op = (String)i$.next();
                    modelAndView.addObject("can" + op.substring(0, 1).toUpperCase() + op.substring(1), Boolean.valueOf(true));
                }
            }
        }

        this.userSession.remove();
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception ex) throws Exception {
        this.userSession.remove();
        if(ex != null) {
            this.log.error(obj.toString(), ex);
        }

    }

    protected void outputResponse(HttpServletResponse response, String str) {
        response.setContentType("text/html; charset=utf-8");

        try {
            PrintWriter e = response.getWriter();
            e.print(str);
            e.close();
        } catch (IOException var4) {
            this.log.error(var4);
        }

    }
}
